//
//  WeatherTool.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/9/26.
//

#import "WeatherTool.h"
#import <CoreLocation/CoreLocation.h>

@interface WeatherTool ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) void(^addressBlock)(NSString *);

@end

@implementation WeatherTool

+ (instancetype)shared{
    static dispatch_once_t onceToken;
    static WeatherTool *sharedManager;
    dispatch_once(&onceToken, ^{
        sharedManager = [[WeatherTool alloc]init];
    });
    
    return sharedManager;
}


- (void)openWeather{
    if([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        [self.locationManager startMonitoringSignificantLocationChanges];
        [self.locationManager requestWhenInUseAuthorization];
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        [[DTKTool getCurrentVC].view showWarning:@"无法获得定位,请开启定位权限"];
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    CLLocation * c = locations.lastObject;
    NSLog(@"当前坐标%@",c);
    double latitude = c.coordinate.latitude;
    double longitude = c.coordinate.longitude;
    [self getApiWithStr:[NSString stringWithFormat:@"%.2f,%.2f",longitude,latitude]];
    [self.locationManager stopUpdatingLocation];
    
    [geoCoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *mark = [placemarks lastObject];
        NSString *cityName = mark.locality;
        NSString *subLocality = mark.subLocality;
        NSString *thoroughfare = mark.thoroughfare;
        if(thoroughfare.length > 0){
            [WeatherModel shared].address = [NSString stringWithFormat:@"%@%@%@",cityName,subLocality,thoroughfare];
        } else {
            [WeatherModel shared].address = [NSString stringWithFormat:@"%@%@",cityName,subLocality];
        }
        NSLog(@"当前的地址是%@", [WeatherModel shared].address);
    }];
    //
    [self.locationManager stopUpdatingLocation];
}

- (void)getApiWithStr:(NSString *)str{
//    NSLog(@"%@---%@",[NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-HH-dd"] ,[WeatherModel shared].hourlyTime);
    if(![[NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM-dd HH"] isEqualToString:[WeatherModel shared].hourlyTime]){///不是今天的数据
        [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"https://devapi.qweather.com/v7/weather/24h?location=%@&key=70fdb6114028407cba78a485cdbe3386",str] parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dict = responseObject;
            WeatherModel * model = [WeatherModel yy_modelWithDictionary:responseObject];
            if([model.code isEqualToString:@"200"]){
                [WeatherModel shared].hourlyTime = [NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-MM-dd HH"];
                [WeatherModel shared].hourly = model.hourly;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
    if(![[NSDate br_stringFromDate:[NSDate new] dateFormat:@"yyyy-HH-dd"] isEqualToString:[WeatherModel shared].dailyTime]){///不是今天的数据
        [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"https://devapi.qweather.com/v7/weather/7d?location=%@&key=70fdb6114028407cba78a485cdbe3386",str] parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dict = responseObject;
            WeatherModel * model = [WeatherModel yy_modelWithDictionary:responseObject];
            if([model.code isEqualToString:@"200"]){
                [WeatherModel shared].dailyTime = [model.updateTime componentsSeparatedByString:@"T"].firstObject;
                [WeatherModel shared].daily = model.daily;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
    
}

@end
